package com.linln.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linln.common.data.MybatisPage;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.business.dao.MapperAttendanceApply;
import com.linln.modules.business.domain.AttendanceApply;
import com.linln.modules.business.domain.Task;
import com.linln.modules.system.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author chaunceyzhong
 */

@Service
public class AttendanceApplyServiceImpl extends ServiceImpl<MapperAttendanceApply, AttendanceApply> {

    @Autowired
    TaskServiceImpl taskService;
    @Autowired
    MapperAttendanceApply mapperAttendanceApply;

    @Transactional(rollbackFor = Exception.class)
    public boolean addAttendanceApply(AttendanceApply attendanceApply) {
        boolean save = this.save(attendanceApply);
        User u = new User();
        u.setId(attendanceApply.getUserId());
        u.setUsername(attendanceApply.getUserName());
        boolean startTask = taskService.startTask(attendanceApply.getId(), 1, u);
        if (save && startTask) {
            return true;
        } else {
            throw new RuntimeException("提交加班申请失败！");
        }
    }


    /**
     * 获取我的加班申请记录
     *
     * @return
     */
    public IPage<AttendanceApply> getMyAttendanceApply() {
        IPage<AttendanceApply> iPage = MybatisPage.pageRequest();
        Long userId = ShiroUtil.getSubject().getId();
        IPage<AttendanceApply> page = mapperAttendanceApply.getMyAttendanceApply(iPage, userId);
        return page;
    }

    /**
     * 获取待审批的加班记录
     *
     * @return
     */
    public IPage<AttendanceApply> getMyAudition() {
        IPage<AttendanceApply> iPage = MybatisPage.pageRequest();
        Long userId = ShiroUtil.getSubject().getId();
        IPage<AttendanceApply> page = mapperAttendanceApply.getMyAttendanceApplyAudition(iPage, userId);
        return page;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean audit(Long taskId, Integer pass) {
        UpdateWrapper<Task> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", taskId);
        updateWrapper.set("status", pass);
        taskService.update(updateWrapper);
        return taskService.update(updateWrapper);
    }


}
